package com.yc;

import com.google.gson.Gson;
import com.yc.util.DBHelper;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "d0401.HyfcNewsServlet", value = "/hyfcnews.s")
public class d0401HyfcNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 判断是否有缓存的新闻
        Jedis jedis = new Jedis("127.0.0.1", 7000);
        // Jedis jedis = new Jedis(); 默认 127.0.0.1:6379
        // jedis ~= jdbc 的连接 + 语句对象

        try{
            final boolean exists = jedis.exists("hyfc_news");

            List<Map<String, Object>> maps;
            Gson gson = new Gson();
            if(exists){
                // 如果有直接返回
                final List<String> list = jedis.lrange("hyfc_news", 0, -1);
                maps = new ArrayList<>();
                list.forEach(json->{
                    final HashMap hashMap = gson.fromJson(json, HashMap.class);
                    maps.add(hashMap);
                });
            } else {
                // 如果没有则到mysql查询
                String sql = "select * from hyfc_news order by intime desc limit 0, 10";
                maps = DBHelper.selectListMap(sql);
                maps.forEach(map->{
                    final String json = gson.toJson(map);
                    // 保存到redis中(缓存)
                    jedis.rpush("hyfc_news", json);
                });
            }
            final String json = gson.toJson(maps);
            response.getWriter().append(json);
        } finally {
            // 关闭 jedis
            jedis.close();
        }
        // 扩展: 新增新闻要更新缓存数据, 删除一个旧的, 新增一个新的
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
